package edu.gzhu.guli.core.oss;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

@Configuration
public class OSSConfiguration {

  private volatile static OSS ossClient;

  private volatile static OSSClientBuilder ossClientBuilder;

  private static String END_POINT;

  private static String ACCESS_KEY_ID;

  private static String ACCESS_KEY_SECRET;

  @Value("${aliyun.bucket-name}")
  private String bucketName;

  @Value("${aliyun.endpoint}")
  public void setEndpoint(String endpoint) {
    OSSConfiguration.END_POINT = endpoint;
  }

  @Value("${aliyun.access-key-id}")
  public void setAccessKeyId(String accessKeyId) {
    OSSConfiguration.ACCESS_KEY_ID = accessKeyId;
  }

  @Value("${aliyun.access-key-secret}")
  public void setAccessKeySecret(String accessKeySecret) {
    OSSConfiguration.ACCESS_KEY_SECRET = accessKeySecret;
  }

  public String getBucketName() {
    return bucketName;
  }

  @Bean
  @Scope("prototype")
  static OSS initOSSClient() {
    if (ossClient == null) {
      synchronized (OSSConfiguration.class) {
        if (ossClient == null) {
          ossClient = initOSSClientBuilder().build(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        }
      }
    }
    return ossClient;
  }

  public static OSSClientBuilder initOSSClientBuilder() {
    if (ossClientBuilder == null) {
      synchronized (OSSConfiguration.class) {
        if (ossClientBuilder == null) {
          ossClientBuilder = new OSSClientBuilder();
        }
      }
    }
    return ossClientBuilder;
  }
}